﻿using AutoMapper;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace Stackoverflow.Results
{
    public class SearchResult<T> : IHttpActionResult where T : class
    {
        public IEnumerable Items { get; set; }
        public int? Total { get; set; }
        private HttpRequestMessage Request { get; set; }

        public SearchResult(HttpRequestMessage request, IEnumerable items, int? total = null)
        {
            Items = items;
            Total = total;
            Request = request;
        }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var result = Mapper.Map<IEnumerable<T>>(Items);

            var responseMessage = Request.CreateResponse(HttpStatusCode.OK, result);
            responseMessage.Headers.Add("Total", Total.ToString());

            return Task.FromResult(responseMessage);
        }
    }

    public static class Extensions
    {
        public static IHttpActionResult CreateSearchResult<T>(this HttpRequestMessage request, IEnumerable items, int? total = null) where T : class
        {
            return new SearchResult<T>(request, items, total);
        }
    }
}